﻿#pragma execution_character_set("utf-8")
#include "mainwindow.h"

#include <QSystemSemaphore>
#include <QApplication>
#include <QLocale>
#include <QTranslator>
#include <QTextCodec>
#include <QSettings>
#include <QDir>
#include "settingdlg.h"

int main(int argc, char *argv[])
{
    //    qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard"));
    int nExitCode=0;
    do
    {
        QApplication a(argc, argv);
        a.setWindowIcon(QIcon(":/log.ico"));

        a.setFont(QFont("Microsoft Yahei", 9));

#if (QT_VERSION < QT_VERSION_CHECK(5,0,0))
#if _MSC_VER
        QTextCodec *codec = QTextCodec::codecForName("gbk");
#else
        QTextCodec *codec = QTextCodec::codecForName("utf-8");
#endif
        QTextCodec::setCodecForLocale(codec);
        QTextCodec::setCodecForCStrings(codec);
        QTextCodec::setCodecForTr(codec);

#else
        QTextCodec *codec = QTextCodec::codecForName("utf-8");
        QTextCodec::setCodecForLocale(codec);
#endif
        QSettings set(SettingDlg::ConfigFile, QSettings::IniFormat);
        QTranslator translator;
        QString baseName = "MD200_cn";
        QString strLanguage = set.value("language", "0").toString();
        int index = strLanguage.toInt();
        switch (index) {
        default:
        case 0:
            set.setValue("language", "0");
            break;
        case 1:
            set.setValue("language", "1");
            baseName = "MD200_en";
            break;
        case 2:
            set.setValue("language", "2");
            baseName = "MD200_vi";
            break;
        }

        if (translator.load(":/i18n/" + baseName)) {
            a.installTranslator(&translator);
        }

        // 定义一个唯一的键
        const QString semaphoreKey = "MyUniqueQtAppSemaphore";

        // 创建一个系统信号量，初始值为1
        QSystemSemaphore semaphore(semaphoreKey, 1, QSystemSemaphore::Create);

        // 尝试获取一个资源
        if (semaphore.acquire()) {
            qDebug() << "Program is running as the first instance.";

            // 在这里添加你的程序逻辑

            // 在程序结束时释放资源
//            semaphore.release();
        } else {
            qDebug() << "Another instance of the program is already running.";
            return 1; // 或者你可以选择显示一个消息框并退出
        }

        MainWindow w;
        w.show();

        semaphore.release();

        nExitCode=a.exec();
    } while(nExitCode==777777);

    return nExitCode;

}
